package com.ecarx.module_log.logexport.controller;

import android.os.CountDownTimer;
import android.os.SystemProperties;
import android.util.Log;

import com.ecarx.library_base.usb.UDiskDevice;
import com.ecarx.library_base.usb.UDiskManager;
import com.ecarx.library_base.usb.UDiskUtil;
import com.ecarx.library_base.usb.brodcast.USBReceiver;

import java.util.Arrays;
import java.util.List;

/**
 * 日志导出控制器
 */
public class LogExportController implements USBReceiver.UsbChangeCallback {

    private static final String TAG = "LogExport";

    private static final String PROP_LOG_COPY = "ecarx.logcopy";
    private static final String PROP_LOG_COPY_RES = "ecarx.logcopy.res";
    private static final String PROP_SUCCEED = "0";
    private static final String PROP_FAILED = "1";

    private CountDownTimer countDownTimer;

    LogExportCallback logExportCallback;
    private boolean isLogExporting;
    private UDiskDevice inUseUDiskDevice;
    private static final String[] LOG_DIR = new String[]{
            "/data/anr/ /data/tombstones/ /data/tcpdump/ /data/log/ /data/McuLog/",
            "/data/log_cluster",
//            "/data/log_gameos",
            "/data/log_hypervisor"
    };

    public LogExportController() {

    }

    /**
     * 初始化
     *
     * @param logExportCallback 回调
     */
    public void init(LogExportCallback logExportCallback) {
        this.logExportCallback = logExportCallback;
        registerReceiver();
    }

    /**
     * 开始导出
     *
     * @param usbFile u盘
     */
    public void start(UDiskDevice usbFile, int index) {
        String resDir = LOG_DIR[index];
        stop();
        //设置拷贝U盘路径
        Log.d(TAG, "start: setprop ecarx.logcopy >> " + usbFile.getInternalPath());
        setProp(PROP_LOG_COPY_RES, resDir);
        setProp(PROP_LOG_COPY, usbFile.getInternalPath());
        setProp("ctl.start", "logcat_copy");

        isLogExporting = true;
        inUseUDiskDevice = usbFile;

        //最长循环五分钟，一次一秒
        countDownTimer = new CountDownTimer(1000 * 60 * 5, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                String prop = getProp(PROP_LOG_COPY, "");
                Log.d(TAG, "onTick: prop " + prop);
                if (PROP_SUCCEED.equals(prop)) {
                    doCallbackFinishEvent(true, "success");
                } else if (PROP_FAILED.equals(prop)) {
                    doCallbackFinishEvent(false, "fail: " + prop);
                }
            }

            @Override
            public void onFinish() {
                Log.d(TAG, "onFinish: time out ");
                //timeout
                doCallbackFinishEvent(false, "time out");
            }
        };


        countDownTimer.start();
    }

    private void doCallbackFinishEvent(boolean isSucceed, String msg) {
        stop();
        logExportCallback.onCopyFinish(isSucceed, msg);
    }

    /**
     * 是否导出中
     */
    public boolean isLogExporting() {
        return isLogExporting;
    }

    /**
     * 停止导出
     */
    public void stop() {
        setProp("ctl.stop", "logcat_copy");
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        isLogExporting = false;
    }

    /**
     * 释放资源
     */
    public void release() {
        unRegisterReceiver();
        stop();
    }

    @Override
    public void onUsbDeviceChanged(boolean isAdd, List<UDiskDevice> uDiskDeviceList) {

        Log.d(TAG, "onUsbDeviceChanged: isAdd " + isAdd + " uDiskDeviceList = " + Arrays.toString(uDiskDeviceList.toArray()));
        if (!isAdd && isLogExporting() && inUseUDiskDevice != null) {
            if (!uDiskDeviceList.contains(inUseUDiskDevice)) {
                doCallbackFinishEvent(false, "U盘识别失败");
                Log.d(TAG, "onUsbDeviceChanged: " + inUseUDiskDevice.getFsLabel() + " is unmount");
            }
        }
        logExportCallback.onUsbChanged(isAdd, uDiskDeviceList);

    }

    public interface LogExportCallback {

        /**
         * 拷贝完成
         *
         * @param isSuccess 成功/失败
         * @param msg       msg
         */
        void onCopyFinish(boolean isSuccess, String msg);

        /**
         * U盘刷新
         *
         * @param isAdd           添加/删除
         * @param uDiskDeviceList U盘列表
         */
        void onUsbChanged(boolean isAdd, List<UDiskDevice> uDiskDeviceList);
    }

    private void setProp(String key, String value) {
        SystemProperties.set(key, value);
    }

    private String getProp(String key, String def) {
        try {
            return SystemProperties.get(key, def);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<UDiskDevice> getUDiskDeviceList() {
        return UDiskUtil.getUDiskDeviceList();
    }


    private void registerReceiver() {
        UDiskManager.getInstance().addUDiskChangeListener(this::onUsbDeviceChanged);
    }

    private void unRegisterReceiver() {
        UDiskManager.getInstance().removeUDiskChangeListener(this::onUsbDeviceChanged);
    }


}
